<?php

declare(strict_types=1);

namespace app\admin\controller;

use app\model\CouponGoods as Model;
use think\Request;
use think\facade\Request as Req;
use think\facade\Db;

class CouponGoods extends Controller
{
    /**
     * 权益商品列表
     */
    public function index()
    {
        $param = input('post.');
        $where = [];
        if (!empty($param['sku_type'])) {
            $where[] = ['sku_type', '=', $param['sku_type']];
            if ($param['sku_type'] != 0) {
                $where[] = ['relate_state',"=",1];
            }
        }
        if (!empty($param['supplier_id'])) {
            $where[] = ['supplier_id', '=', $param['supplier_id']];
        }
        if (!empty($param['category_id'])) {
            $brandIds = Db::name('rs_relate')
                ->where('cate_id', $param['category_id'])
                ->where('status', 1)
                ->column('brand_id');
            if (empty($brandIds)) {
                $where[] = ['id', '=', -1];
            } else {
                $where[] = ['brand_id', 'in', $brandIds];
            }
        }
        if (isset($param['relate_state']) && $param['relate_state'] != -1) {
            $where[] = ['relate_state', '=', $param['relate_state']];
        }
        if (isset($param['shelf_state']) &&  $param['shelf_state'] != -1) {
            $where[] = ['shelf_state', '=', $param['shelf_state']];
        }
        if (isset($param['sku_state']) &&  $param['sku_state'] != -1) {
            $where[] = ['sku_state', '=', $param['sku_state']];
        }
        if (!empty($param['key'])) {
            $where[] = ['id|goods_name',"like","%".$param['key']."%"];
        }

        $data = Db::name('coupon_goods')
            ->where($where)
            ->paginate($this->getPaginate())
            ->toArray();

        $supplier = Db::name('base_supplier')
            ->where('serv_type', PRODUCT_COUPON_SERV)
            ->order('id desc')
            ->column('name', 'id');

        // 处理状态相关显示
        if ($data['data']) {
            $model = new Model;

            $brandIds = array_unique(array_column($data['data'], 'brand_id'));
            $brand = Db::name('rs_brand')
                ->whereIn('id', $brandIds)
                ->column('brand_name', 'id');

            $brandCate = Db::name('rs_relate')
                ->field('cate_id, brand_id')
                ->where('status', 1)
                ->whereIn('brand_id', $brandIds)
                ->select()
                ->toArray();
            $cateIds = array_unique(array_column($brandCate, 'cate_id'));
            $cate = Db::name('rs_cate')
                ->whereIn('id', $cateIds)
                ->whereNull('deleted_at')
                // ->where('status', 1)
                ->column('cate_name', 'id');
            $brandList = [];
            foreach ($brandCate as $v) {
                if (!empty($cate[$v['cate_id']])) {
                    $brandList[$v['brand_id']][] = $cate[$v['cate_id']];
                }
            }

            foreach ($data['data'] as $k => $v) {
                $data['data'][$k]['sku_state_text'] = $model->skuState[$v['sku_state']];
                $data['data'][$k]['relate_state_text'] = $model->relateState[$v['relate_state']];
                $data['data'][$k]['shelf_state_text'] = $model->shelfState[$v['shelf_state']];
                $data['data'][$k]['sku_type_text'] = $model->skuType[$v['sku_type']];
                $data['data'][$k]['market_price'] = fen2yuan($v['market_price']);
                $data['data'][$k]['cost_price'] = fen2yuan($v['cost_price']);
                $data['data'][$k]['sale_price'] = fen2yuan($v['sale_price']);

                $data['data'][$k]['supplier_name'] = $supplier[$v['supplier_id']] ?? '';
                $data['data'][$k]['brand_name'] = $brand[$v['brand_id']] ?? '';
                if (!empty($brandList[$v['brand_id']])) {
                    $data['data'][$k]['cate_name'] = implode('/', $brandList[$v['brand_id']]);
                } else {
                    $data['data'][$k]['cate_name'] = '';
                }
            }
        }
        $data['excel_url'] = Req::domain().'/coupon.xlsx';
        $data['supplierList'] = $supplier;

        return success('', $data);
    }
    /**
     *  权益商品列表
     */
    public function indexOld(Request $request)
    {
        $param = $request->only(['key'=>'','sku_type' => '', 'relate_state', 'shelf_state', 'supplier' => '', 'sku_state', 'category_id' => 0]);
        $where = [];
        if ($param['sku_type']) {
            $where[] = ['sku_type', '=', $param['sku_type']];
            if ($param['sku_type'] != 0) {
                $where[] = ['relate_state',"=",1];
            }
        }
        if (!empty($param['supplier'])) {
            $where[] = ['b.id|b.name', '=', $param['supplier']];
        }
        if ($param['category_id']) {
            $where[] = ['category_id', '=', $param['category_id']];
        }
        if (isset($param['relate_state']) && $param['relate_state'] != -1) {
            $where[] = ['relate_state', '=', $param['relate_state']];
        }
        if (isset($param['shelf_state']) &&  $param['shelf_state'] != -1) {
            $where[] = ['shelf_state', '=', $param['shelf_state']];
        }
        if (isset($param['sku_state']) &&  $param['sku_state'] != -1) {
            $where[] = ['sku_state', '=', $param['sku_state']];
        }
        if ($param['key']) {
            $where[] = ['a.id|a.goods_name',"like","%".$param['key']."%"];
        }
        $model = new Model();
        $modelQuery = $model->alias("a")
            ->field("a.*,b.name as supplier_name,c.brand_name")
            ->join("base_supplier b", "b.id = a.supplier_id", "left")
            ->join("rs_brand c", "c.id = a.brand_id", "left");
        if ($where) {
            $modelQuery = $modelQuery->where($where);
        }

        $data = $modelQuery->paginate($this->getPaginate())->toArray();
        // 处理状态相关显示
        if ($data['data']) {
            foreach ($data['data'] as $k => $v) {
                $data['data'][$k]['sku_state_text'] = $model->skuState[$v['sku_state']];
                $data['data'][$k]['relate_state_text'] = $model->relateState[$v['relate_state']];
                $data['data'][$k]['shelf_state_text'] = $model->shelfState[$v['shelf_state']];
                $data['data'][$k]['sku_type_text'] = $model->skuType[$v['sku_type']];
                $data['data'][$k]['market_price'] = fen2yuan($v['market_price']);
                $data['data'][$k]['cost_price'] = fen2yuan($v['cost_price']);
                $data['data'][$k]['sale_price'] = fen2yuan($v['sale_price']);
            }
        }
        $data['excel_url'] = Req::domain().'/coupon.xlsx';

        return success('', $data);
    }

    /**
     * @api {POST} /admin/couponGoods/relate 商品对接状态变更
     * @apiDescription 商品对接状态变更,取消对接的时候 同时把商品下价？
     * @apiName couponGoodsRelate 商品对接状态变更
     * @apiGroup Admin2_0
     * @apiParam {String} id id或者批量勾选的id(例如 1,2,4)
     * @apiParam {Number=0,1} relate_state 对接商品或者删除对接
     * @apiUse BaseReturn
     * @apiVersion 1.0.0
     */
    public function relate(Request $request)
    {
        $rules = [
            'id' => 'require',
            'relate_state' => 'require',
        ];
        $messages = [
            'id.require' => '请选择',
            'relate_state.require' => '非法状态',
        ];
        $param = $request->only(['id', 'relate_state']);
        if ($msg = dmjValidate($rules, $messages, $param)) {
            return fail($msg);
        }
        if (!in_array($param['relate_state'], [0, 1])) {
            return fail('非法取值');
        }

        $idArr = explode(',', $param['id']);
        if (1 == count($idArr)) {
            $model = Model::find($idArr[0]);
            if (!$model) {
                return fail('数据不存在，请刷新页面看看');
            }
            $model->relate_state = $param['relate_state'];
            if (0 == $param['relate_state']) {
                $model->shelf_state = 0;
            }
            $res = $model->save();
        } else {
            $model = new Model();
            $list = [];
            foreach ($idArr as $k => $v) {
                $arrv = ['id' => $v, 'relate_state' => $param['relate_state']];
                if (0 == $param['relate_state']) {
                    $arrv['shelf_state'] = 0;
                }
                $list[] = $arrv;
            }
            $res = $model->saveAll($list);
        }

        return success();
    }

    /**
     * @api {POST} /admin/couponGoods/shelf 商品上下架
     * @apiDescription 商品上下架
     * @apiName couponGoodsShelf 商品上下架
     * @apiGroup Admin2_0
     * @apiParam {String} [id] id或者批量勾选的id(例如 1,2,4)
     * @apiParam {Number=0,1} shelf_state 对接商品或者删除对接
     * @apiUse BaseReturn
     * @apiVersion 1.0.0
     */
    public function shelf(Request $request)
    {
        $rules = [
            'id' => 'require',
            'shelf_state' => 'require',
        ];
        $messages = [
            'id.require' => '请选择',
            'shelf_state.require' => '非法状态',
        ];
        $param = $request->only(['id', 'shelf_state']);
        if ($msg = dmjValidate($rules, $messages, $param)) {
            return fail($msg);
        }
        if (!in_array($param['shelf_state'], [0, 1])) {
            return fail('非法取值');
        }

        $idArr = explode(',', $param['id']);

        // 上架需要判断商品是否已经对接，未对接的不让上架
        if (1 == $param['shelf_state']) {
            if (1 == count($idArr)) {
                $model = Model::where('relate_state', 0)->find($idArr[0]);
                if ($model) {
                    return fail('该商品未对接，无法上架，请先对接');
                }
            } else {
                $existsIdArr = Model::where('relate_state', 0)->whereIn('id', $idArr)->column('id');
                if ($existsIdArr) {
                    return fail('id【'.implode(',', $existsIdArr).'】未对接，无法上架，请先对接');
                }
            }
        }

        if (1 == count($idArr)) {
            $model = Model::find($idArr[0]);
            if (!$model) {
                return fail('数据不存在，请刷新页面看看');
            }
            $model->shelf_state = $param['shelf_state'];
            $res = $model->save();
        } else {
            $model = new Model();
            $list = [];
            foreach ($idArr as $k => $v) {
                $list[] = ['id' => $v, 'shelf_state' => $param['shelf_state']];
            }
            $res = $model->saveAll($list);
        }

        return success();
    }

    /**
     * @api {POST} /admin/couponGoods/setPrice 售价修改
     * @apiDescription 售价修改
     * @apiName couponGoodsSetPrice 售价修改
     * @apiGroup Admin2_0
     * @apiParam {String} id id或者批量勾选的id(例如 1,2,4)
     * @apiParam {Number} sale_price 售价(单位元,保留两位小数)
     * @apiUse BaseReturn
     * @apiVersion 1.0.0
     */
    public function setPrice(Request $request)
    {
        $rules = [
            'id' => 'require',
            'sale_price' => 'require|float',
        ];
        $messages = [
            'require' => '请填写',
            'float' => '请输入数字格式',
        ];
        $param = $request->only(['id', 'sale_price']);
        if ($msg = dmjValidate($rules, $messages, $param)) {
            return fail($msg);
        }
        if ($param['sale_price'] <= 0) {
            return fail('价格设置不能小于0');
        }

        $paramSalePrice = $param['sale_price'];
        $param['sale_price'] = intval($param['sale_price'] * 100);
        if ($paramSalePrice * 100 != $param['sale_price']) {
            return fail('价格设置小数点后最多两位数');
        }

        $model = Model::find($param['id']);
        if (!$model) {
            return fail('数据不存在，请刷新页面确认');
        }
        if ($param['sale_price'] > $model->cost_price) {
            return fail('价格设置不能小于成本价');
        }
        $model->sale_price = $param['sale_price'];
        if (!$model->save()) {
            return fail();
        }

        return success();
    }

    /**
     * 对接商品
     */
    public function optionRelate()
    {
        $goods = new Model();
        $data = input('post.');
        return $goods->optionRelate($data);
    }
    /**
     * 上下架商品
     */
    public function optionShelf()
    {
        $goods = new Model();
        $data = input('post.');
        return $goods->optionShelf($data);
    }
    /**
     *   修改销售价
     */
    public function optionSalePrice()
    {
        $goods = new Model();
        $data = input('post.');
        return $goods->optionSalePrice($data);
    }

    /**
     * 充值类型
     */
    public function rechargeType()
    {
        $goods = new Model();
        $data = input('post.');
        return $goods->rechargeType($data);
    }
}
